import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/*
 * @lc app=leetcode.cn id=49 lang=java
 *
 * [49] 字母异位词分组
 */

// @lc code=start
class Solution {
    public List<List<String>> groupAnagrams(String[] strs) {
        Map<String, List<String>> map = new HashMap<String, List<String>>();
        for (String string : strs) {
            int[] counts = new int[26];
            for (int i = 0; i < string.length(); i++) {
                counts[string.charAt(i) - 'a']++;
            }
            StringBuffer sb = new StringBuffer();
            // 将每个出现次数大于 0 的字母和出现次数按顺序拼接成字符串，作为哈希表的键
            for (int i = 0; i < 26; i++) {
                if(counts[i] != 0){
                    sb.append((char)(i + 'a'));
                    sb.append(counts[i]);
                }
            }
            String key = sb.toString();
            List<String> list = map.getOrDefault(key, new ArrayList<>());
            list.add(string);
            map.put(key, list);
        }
        return new ArrayList<>(map.values());
    }
}
// @lc code=end

